//
//  DeviceNavcationVC.m
//  KEREN
//
//  Created by MW on 2023/4/14.
//

#import "DeviceNavcationVC.h"
#import "KRLocationCell.h"
//#import <AMapSearchKit/AMapSearchKit.h>

@interface DeviceNavcationVC ()<MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITextField *textField;
@property (nonatomic, assign) CLLocationCoordinate2D location;
//目的地经纬度
@property (nonatomic, assign) CGFloat longitude;
@property (nonatomic, assign) CGFloat latitude;

//目前所在地经纬度
@property (nonatomic, assign) CGFloat currentLatitude;
@property (nonatomic, assign) CGFloat currentLongitude;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic, strong) UITableView *locationListTableView;
@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, strong) NSString *pointName;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) MAPointAnnotation *centerCoordinate;
@end

@implementation DeviceNavcationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"骑行导航"];
    self.rightClickBlock = ^(void){
      
    };
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 56 + STATUSBAR_HEIGHT, DEVICE_WIDTH, 60)];
    whiteView.backgroundColor = Whire_Color;
    [self.view addSubview:whiteView];
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(24, 10, DEVICE_WIDTH - 48 - 60, 40)];
    [whiteView addSubview:_textField];
    _textField.placeholder = @"请输入目的地";
    _textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 12, 0)];
    _textField.layer.cornerRadius = 12;
    _textField.clipsToBounds = YES;
    _textField.layer.borderWidth = 1;
    _textField.layer.borderColor = Color_borderColor;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    _textField.textColor = Color_333333;
    _textField.rightViewMode = UITextFieldViewModeNever;
    _textField.clearButtonMode = UITextFieldViewModeAlways;
    UIButton *clean = [_textField valueForKey:@"_clearButton"]; //key是固定的
    [clean setImage:[UIImage imageNamed:@"clear"] forState:UIControlStateNormal];

    _textField.font = Font(16);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:_textField];

    UIButton *navBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [whiteView addSubview:navBtn];
    [navBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.centerY.equalTo(whiteView);
        make.width.height.offset(40);
    }];
    [navBtn setImage:[UIImage imageNamed:@"ponit_navgation"] forState:UIControlStateNormal];

    [navBtn addTarget:self action:@selector(pointNavcation) forControlEvents:UIControlEventTouchUpInside];
    
    //    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 56 + STATUSBAR_HEIGHT + 60, DEVICE_WIDTH, DEVICE_HEIGHT - 56 - STATUSBAR_HEIGHT)];
    _mapView.delegate = self;
    _mapView.zoomLevel = 12;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArrM.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    footView.backgroundColor = [UIColor clearColor];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KRLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRLocationCell"];
    NSDictionary *dict = self.dataArrM[indexPath.row];
    cell.nameLbl.text = dict[@"name"];
    if(dict[@"address"] && [dict[@"address"] isKindOfClass:[NSString class]]){
        NSString *address = dict[@"address"];
        if(address.length > 0){
            cell.addressLbl.text = [NSString stringWithFormat:@"%@%@",dict[@"district"],dict[@"address"]];
        }else{
            cell.addressLbl.text = [NSString stringWithFormat:@"%@",dict[@"district"]];
        }
    }else{
        cell.addressLbl.text = [NSString stringWithFormat:@"%@",dict[@"district"]];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dict = self.dataArrM[indexPath.row];
    NSArray *array = [dict[@"location"] componentsSeparatedByString:@","];
    self.longitude = [array[0] floatValue];
    self.latitude = [array[1] floatValue];
    self.pointName = dict[@"name"];
    self.textField.text = self.pointName;
    self.locationListTableView.hidden = YES;
    [self.view endEditing:YES];
    
    
    //设置地图的定位中心点坐标
    //将点添加到地图上，即所谓的大头针
    CLLocationCoordinate2D coor ;
    coor.latitude = self.latitude;
    coor.longitude = self.longitude;
    self.centerCoordinate.coordinate = coor;
    _mapView.centerCoordinate = coor;
    [_mapView addAnnotation:_centerCoordinate];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }

    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.frame = CGRectMake(0, 0, 20, 24);
        annotationView.canShowCallout = NO;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
        annotationView.image = [UIImage imageNamed:@"point"];
//        _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 0)];
//        _rightButton.backgroundColor = [UIColor whiteColor];
//        [_rightButton setTitleColor:Color_86898E forState:UIControlStateNormal];
//        _rightButton.titleLabel.font = Font(14);
//        _rightButton.titleLabel.numberOfLines = 0;
//        [_rightButton setTitle:self.locationStr forState:UIControlStateNormal];
//        annotationView.leftCalloutAccessoryView = _rightButton;

        return annotationView;
    }

    return nil;
}



-(void)textFiledEditChanged:(NSNotification*)notification{
    WEAKSELF
    if(_textField.text.length > 0 && _textField.markedTextRange == nil){
        NSString *urlStr = [NSString stringWithFormat:@"https://restapi.amap.com/v3/assistant/inputtips?keywords=%@&key=%@&location=%@",_textField.text,GDWebKey,[NSString stringWithFormat:@"%lf,%lf",GDLOCATION.coordinate.longitude,GDLOCATION.coordinate.latitude]];//location
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        [NetworkingTool GET:urlStr parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            [[KRAlartManager shareInstance] hidenLodingImageView];
            if([response[@"status"] intValue] == 1){
                if([response[@"tips"] isKindOfClass:[NSArray class]]){
                    NSArray *tipsArr = response[@"tips"];
                    [weakSelf.dataArrM removeAllObjects];
                    for (int i = 0; i < tipsArr.count; i++) {
                        NSDictionary *dict = tipsArr[i];
                        if(dict[@"location"] && [dict[@"location"] isKindOfClass:[NSString class]]){
                            NSString *location = dict[@"location"];
                            if( location.length > 0){
                                [weakSelf.dataArrM addObject:dict];
                            }
                        }
                    }
                }

            }
            if(weakSelf.dataArrM.count > 0){
                [weakSelf.locationListTableView reloadData];
                weakSelf.locationListTableView.hidden = NO;
            }else{
                weakSelf.locationListTableView.hidden = YES;
            }
            if(weakSelf.textField.text.length == 0){
                weakSelf.locationListTableView.hidden = YES;
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
        }];
    }else{
        weakSelf.locationListTableView.hidden = YES;
    }
}


- (void)getLocation{
    if(_textField.text.length == 0){
        [[KRAlartManager shareInstance] showAlert:@"请输入目的地"];
        return;
    }
    WEAKSELF
    [self.geocoder geocodeAddressString:_textField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    
        if (placemarks.count > 0 && error == nil) {
        
            CLPlacemark *placemark = placemarks.firstObject;
        
            weakSelf.longitude = placemark.location.coordinate.longitude;
            weakSelf.latitude = placemark.location.coordinate.latitude;
            [self pointNavcation];
        }
        else if (placemarks.count == 0 && error == nil){
            DDLogInfo(@"placemarks元素为0");
        }else if(error != nil){
            DDLogInfo(@"an arror occurred = %@", error);
        }
    }];

}


- (MAPointAnnotation *)centerCoordinate{
    if(!_centerCoordinate){
        _centerCoordinate = [[MAPointAnnotation alloc] init];
    }
    return _centerCoordinate;
}

- (void)pointNavcation{
    [self.view endEditing:YES];
    if(_textField.text.length == 0){
        [[KRAlartManager shareInstance] showAlert:@"请输入目的地"];
        return;
    }
    [[KRAlartManager shareInstance] showPointNavcation:_longitude latitude:_latitude pointName:_textField.text];
}
- (CLGeocoder *)geocoder{

    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (UITableView *)locationListTableView{
    if(!_locationListTableView){
        _locationListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 56 + STATUSBAR_HEIGHT + 60, DEVICE_WIDTH, DEVICE_HEIGHT - 56 - STATUSBAR_HEIGHT - 60 - 280)];
        _locationListTableView.backgroundColor = Whire_Color;
        _locationListTableView.delegate = self;
        _locationListTableView.dataSource = self;
        _locationListTableView.rowHeight = 70;
        _locationListTableView.estimatedRowHeight = 0;
        _locationListTableView.estimatedSectionFooterHeight = 0;
        _locationListTableView.estimatedSectionHeaderHeight = 0;
        if (@available(iOS 15.0, *)) {
            _locationListTableView.sectionHeaderTopPadding = 0;
        }
        _locationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_locationListTableView registerNib:[UINib nibWithNibName:@"KRLocationCell" bundle:nil] forCellReuseIdentifier:@"KRLocationCell"];
        [self.view addSubview:_locationListTableView];

    }
    return _locationListTableView;
}

-(NSMutableArray *)dataArrM{
    if(!_dataArrM){
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}
@end
